package c10;

import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 串行执行阶段1，阶段2，阶段3，多个线程执行该任务时，必须保证所有线程的阶段n全部完成之后才能继续下一个阶段
 */
public class CyclicBarrierTest2 {
    private static CyclicBarrier cyclicBarrier=new CyclicBarrier(2);

    public static void main(String[] args) {
        ExecutorService es= Executors.newFixedThreadPool(2);
        es.submit(new Runnable() {
            @Override
            public void run() {

                try {
                    System.out.println(Thread.currentThread()+" step1");
                    cyclicBarrier.await();
                    System.out.println(Thread.currentThread()+" step2");
                    cyclicBarrier.await();
                    System.out.println(Thread.currentThread()+" step3");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        es.submit(new Runnable() {
            @Override
            public void run() {

                try {
                    System.out.println(Thread.currentThread()+" step1 ");
                    cyclicBarrier.await();
                    System.out.println(Thread.currentThread()+" step2 ");
                    cyclicBarrier.await();
                    System.out.println(Thread.currentThread()+" step3 ");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        es.shutdown();

    }

}
